package com.pjb.springbootjjwt.store.server;

import com.pjb.springbootjjwt.store.entity.Line;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import com.pjb.springbootjjwt.store.utils.StringUtil;
import org.apache.commons.lang3.ObjectUtils;

import java.util.*;

public class QueryUtil {

    public static List<Line> join(List<List<Line>> from) {
        if (ObjectUtils.isEmpty(from)) return new ArrayList<>();

        List<Line> l = from.remove(0);
        while (!from.isEmpty()) {
            List<Line> i = from.remove(0);
            l = joinTwo(l, i);
        }
        return l;
    }

    private static List<Line> joinTwo(List<Line> from, List<Line> to) {
        List<Line> r = new ArrayList<>();
        for (Line i : from) {
            for (Line j : to) {
                Line l = new Line();
                List<String> data = new ArrayList<>(i.getData());
                data.addAll(j.getData());
                String id = StringUtil.md5(FileUtil.jsonStr(data));
                l.setKey(id);
                l.setData(data);
                r.add(l);
            }
        }
        return r;
    }

    private static List orderby(List<Line> list, int index) {
        TreeMap treeMap = new TreeMap();
        for (Line line : list) {
            String param = line.getData().get(index);
            treeMap.put(param, line);
        }
        Collection<Line> valueCollection = treeMap.values();
        List<Line> r = new ArrayList<Line>(valueCollection);
        return r;
    }


    public static void main(String[] args) throws Exception {
        Line l1 = new Line();
        l1.setKey("0001");
        l1.setData(new ArrayList<>(Arrays.asList("a1", "ab", "31")));
        Line l2 = new Line();
        l2.setKey("0011");
        l2.setData(new ArrayList<>(Arrays.asList("a2", "ab", "21")));
        Line l3 = new Line();
        l3.setKey("0011");
        l3.setData(new ArrayList<>(Arrays.asList("a2", "ab", "42")));
        List<Line> from = new ArrayList<>();
        from.add(l1);
        from.add(l2);
        from.add(l3);

        List<Line> to = orderby(from, 2);
        System.out.println(to);
    }
}
